package com.sender.location;

import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;

/**@author zsr: 该类用于获取地理位置信息
 */
public class LocationInfo {
	private static final int TWO_MINUTES = 1000 * 60 * 2;	//用于判断location的新旧程度
	private static final long FIRST_LISTENING_TIME = 10000;	//第一次监听时间，时间越长定位越精确
	private Location location = null;
	private LocationManager locationManager = null;
	private Context context = null;
	private MyLocationListener myLocationListener = new MyLocationListener(location);
	private boolean flag = true;
	
	/**构造函数
	 * @param context 用于获取系统服务，从而得到位置监听功能
	 */
	LocationInfo(Context context){
		this.context = context;
	}
	
	/**开始监听位置信息 */
	private void start(){
		Looper.prepare();
		locationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
		locationManager.requestLocationUpdates(getBetterProvider(), 0, 0, myLocationListener);
		
	}
	
	/**获取地理位置(费时操作，阻塞线程)
	 * @return double[]: double[0]经度 double[1]纬度
	 */
	public void startListening(Handler handler){
		System.out.println("1");
		start();
		Message msg = handler.obtainMessage();
		double[] lalon = new double[2];
		try {
			Thread.sleep(FIRST_LISTENING_TIME);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		while(flag){
			if(location != null){
				lalon[0] = location.getLongitude();
				lalon[1] = location.getLatitude();
				msg.obj = lalon;
				msg.sendToTarget();
				System.out.println("send msg");
			}
			System.out.println("2");
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		Looper.loop();
	}
	
	/**停止监听*/
	private void stop(){
		this.flag = false;
		locationManager.removeUpdates(myLocationListener);
	}
	
	/** 获取较好的Location provider
	 * @return String
	 */
	private String getBetterProvider(){
		return LocationManager.GPS_PROVIDER;
	}
	
	/**location监听器*/
	private class MyLocationListener implements LocationListener{
		private Location currentBestLocation = null;
		MyLocationListener(Location location){
			this.currentBestLocation = location;
		}
		public void onLocationChanged(Location location) {
			if(isBetterLocation(location, currentBestLocation))this.currentBestLocation = location;
			System.out.println("new location");
		}

		public void onProviderDisabled(String provider) {
			
		}

		public void onProviderEnabled(String provider) {
			
		}

		public void onStatusChanged(String provider, int status, Bundle extras) {
			
		}
		
		/** 判断新获取的location是否比旧的location好
		  * @param location	新获取的location
		  * @param currentBestLocation	当前location
		  */
		protected boolean isBetterLocation(Location location, Location currentBestLocation){
			if (currentBestLocation == null) {
				return true;
		    }
		
		    //比较location的新旧
		    long timeDelta = location.getTime() - currentBestLocation.getTime();
		    boolean isSignificantlyNewer = timeDelta > TWO_MINUTES;
		    boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES;
		    boolean isNewer = timeDelta > 0;
		
		    //location时间间隔超过两分钟则强制更新
		    if (isSignificantlyNewer) {
		        return true;
		    } else if (isSignificantlyOlder) {
		        return false;
		    }
		
		    //比较精确度
		    int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation.getAccuracy());
		    System.out.println("locationn accuracy: " + location.getAccuracy());
		    System.out.println("current location accuracy: " + currentBestLocation.getAccuracy());
		    boolean isLessAccurate = accuracyDelta > 0;
		    boolean isMoreAccurate = accuracyDelta < 0;
		    boolean isSignificantlyLessAccurate = accuracyDelta > 200;
		
		    boolean isFromSameProvider = isSameProvider(location.getProvider(),
		            currentBestLocation.getProvider());
		
		    //结合时间和精度比较
		    if (isMoreAccurate) {
		        return true;
		    } else if (isNewer && !isLessAccurate) {
		        return true;
		    } else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) {
		        return true;
		    }
		    return false;
		}
		
		/**检测两个provider是否相同*/
		private boolean isSameProvider(String provider1, String provider2) {
		    if (provider1 == null) {
		      return provider2 == null;
		    }
		    return provider1.equals(provider2);
		}
    }
}
